
from collections import defaultdict
from directed_graph_util import *

__all__ = ['build_from_relation_string', 'build_directed_graph', 'build_classic_directed_graph', 'build_link_list_like_graph']

def build_from_relation_string(relation_str):
    # relation_str = "1,2,3#2,3#3,2"     # 1指向2,3, 2指向3, 3指向2
    # graph = None
    nodes = {}      # {label : DirectedGraphNode}

    def get_node(label):
        if label not in nodes:
            nodes[label] = DirectedGraphNode(label)
        return nodes[label]

    relations = relation_str.split('#')
    for rel in relations:
        labels = rel.split(',')

        src_node = get_node(labels[0])
        if labels[0] == '3':
            print('labels %s' % labels)

        for label in labels[1:]:
            dst_node = get_node(label)
            src_node.neighbors.append(dst_node)

    graph = list(nodes.values())
    return graph

def build_directed_graph():
    # 1--->3---------->5
    # |^  /            |
    # v \v             v
    # 2->4------------>6

    # {1,2,3,4}是一个连通分量, {5}, {6}分别是两个连通分量
    u1 = DirectedGraphNode(1)
    u2 = DirectedGraphNode(2)
    u3 = DirectedGraphNode(3)
    u4 = DirectedGraphNode(4)
    u5 = DirectedGraphNode(5)
    u6 = DirectedGraphNode(6)

    u1.neighbors = [u3, u2]
    u2.neighbors = [u4]
    u3.neighbors = [u4, u5]
    u4.neighbors = [u1, u6]
    u5.neighbors = [u6]

    # graph = [u1, u2, u3]
    # graph = [u2, u1, u3]
    # graph = [u3, u2, u1]
    graph = [u1, u2, u3, u4, u5, u6]
    return graph

def build_link_list_like_graph():
    # relation_str = '1,2#2,3#3,1'
    # relation_str = '1,2#2,3'
    # relation_str = '1,2#2,1,3#3,2'
    relation_str = '1,2#2,1,3#3,2'
    return build_from_relation_string(relation_str)

def build_classic_directed_graph():
    relation_str = "a,b#b,c,e,f#c,d,g#d,c,h#e,a,f#f,g#g,f#h,d,g"
    return build_from_relation_string(relation_str)

def test_build_from_str():
    # relation_str = "1,2,3#2,3#3,2"     # 1指向2,3, 2指向3, 3指向2
    relation_str = "a,b#b,c,e,f#c,d,g#d,c,h#e,a,f#f,g#g,f#h,d,g"
    graph = build_from_relation_string(relation_str)
    for node in graph:
        print(node)
        for nei in node.neighbors:
            print("----> %s" % nei)
        print()
        # print(node.neighbors)

def main():
    print("start main")
    test_build_from_str()

if __name__ == "__main__":
    main()
